#include <iostream>
#include <vector>
#include <fstream>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <algorithm> 
 #include <ctime>
using namespace std;
//John Talbot 2015
//Point distance program!
//terminal syntax is "./dist <desa_pour_points> <desa_flow_realtions> <output_file> 
//Needs revision, coming soon.
//////////////////////////////////////////////////////////////////////////
class desa{
 public:
  int x;
  int y;
  string id;
  desa(int , int, string);
  int operator+(desa &d);
  bool operator < (const desa & d) const
    {return (id < d.id);}
};

bool comp(desa d, desa i)
     {
    return (d.id < i.id);
      }



void  readAndSort(std::vector<desa> &v, std::vector<string> & u, string filename);
void engageDistances(std::vector<desa>& v, std::vector<string> & u, string filename, string outfile);

/////////////////////////////////////////////////////////////////////////////////
//
int main(int argc, char *argv[]){
int start_s=clock();



	
  cout.precision(15);
  std::vector<desa> v;
  std::vector<string> u;
  string file_pour_points(argv[1]);
  string file_flow_relations(argv[2]);
  string outfile(argv[3]);

  readAndSort(v,u,file_pour_points);
  engageDistances(v,u,file_flow_relations, outfile);
int stop_s=clock();
cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC) << endl;
}
///////////////////////////////////////////////////////////////////////////////
  
void  readAndSort(std::vector<desa>& v, std::vector<string>& u, string filename){
  string kill2;
  string kill;
  string id;
  string id2;
  string x;
  string y;

  std::ifstream readin;

  readin.open(filename);
  cout<<"Loading...\n";
  while(!readin.eof()){
    readin>> kill >> x >> y >> id >> kill2;
    desa * d= new desa( stoi(x) , stoi(y) , id );
    v.push_back(*d);
    u.push_back(id);
    delete d;
  
    
   }
  cout<<"Sorting...\n";
  std::sort(v.begin(),v.end()-1);
  std::sort(u.begin(),u.end()-1);

  
 
}

void engageDistances(std::vector<desa>& v, std::vector<string>& u, string filename, string outfile){
  string kill1,kill2,id1,id2;
  ifstream readin;
  int dist;
  ofstream writeOut;
  int index1, index2;
  writeOut.open(outfile);
  readin.open(filename);
  cout<<"Searching"<<endl;
  while(!readin.eof()){
    readin >> kill1 >> kill2 >> id1 >> id2;
    std::vector<string>::iterator itr1;
    std::vector<string>::iterator itr2;
    itr1=std::lower_bound(u.begin(), u.end()-1,id1);
    itr2=std::lower_bound(u.begin(), u.end()-1,id2);
    index1=itr1-u.begin();
    index2=itr2-u.begin();
    writeOut<< v[index1].id <<" "<<v[index2].id <<" "<<v[index1]+v[index2]<<"\n";

  }
  readin.close();
  writeOut.close();
}

 

desa::desa(int xIn, int yIn, string idIn){
  x=xIn;
  y=yIn;
  id=idIn;
}

int desa::operator+(desa &d){
  float a2=pow((x-d.x),2);
float b2=pow((y-d.y),2);
return sqrt(a2+b2);
  }
